package com.hngy.minio.service;

import com.hngy.minio.properties.MinioConfigurationProperties;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;

/**
 * @name: MinioService
 * @Author: 提莫大熊猫
 * @Date: 2023/8/21
 */
@Service
public class MinioService {

    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioConfigurationProperties properties;

    /**
     * 上传文件
     *
     * @param bytes 文件二进制
     * @param filename 文件名
     * @return 文件在服务器中的地址
     */
    public String upload(byte[] bytes, String filename) {
        ByteArrayInputStream is = new ByteArrayInputStream(bytes);
        PutObjectArgs build = PutObjectArgs.builder()
                .object(filename)
                .bucket(properties.getBucket())
                .stream(is, is.available(), -1)
                .build();
        try {
            minioClient.putObject(build);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件上传失败");
        }

        StringBuilder stringBuilder = new StringBuilder(properties.getEndpoint());

        stringBuilder.append("/")
                .append(properties.getBucket())
                .append("/")
                .append(filename);

        return stringBuilder.toString();
    }
}
